﻿using Furion;
using Furion.DataEncryption;
using Furion.DistributedIDGenerator;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.RemoteRequest.Extensions;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Mrhd.Core.Entities;
using Mrhd.Core.Extensions;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Mrhd.Application
{
    /// <summary>
    /// 移动端服务
    /// </summary>
    public class MobileAppService : IDynamicApiController
    {
        private readonly IMobileService _service;
        private readonly IDistributedCache _distributedCache;
        public MobileAppService(IMobileService service,
            IDistributedCache distributedCache)
        {
            _service = service;
            _distributedCache = distributedCache;
        }

        /// <summary>
        /// 用户进入小程序后的初始化工作
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetInit()
        {
            var mobileId = App.User?.FindFirstValue("mobileId");
            // 读取用户绑定的商户
            var businesses = (await _service.GetBindingBusinessAsync(int.Parse(mobileId))).Adapt<List<BusinessDto>>();
            // 读取系统菜单
            var menus = (await _service.GetMenusAsync()).Adapt<List<ProductTypeDto>>();
            var result = new
            {
                businesses,
                menus
            };
            return result;
        }

        /// <summary>
        /// 用户信息授权
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<UserMobileDto> PostGrant(UserMobileDto user)
        {
            user.FaceUrl = await SaveFaceAsync(user.FaceUrl);
            user.Id = App.User.FindFirst("mobileId").Value.ToInt();
            var userinfo = await _service.GrantAsync(user.Adapt<UserMobileEntity>());
            return userinfo.Adapt<UserMobileDto>();
        }

        /// <summary>
        /// 读取用户手机号
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<string> PostPhone(PhoneDto data)
        {
            var encrytedData = data.encryptedData;                                                  // 加密字符串
            var iv = data.iv;                                                                       // 向量
            var mobileId = App.User?.FindFirstValue("mobileId").ToInt();                            // 移动端用户id
            var sessionKey = await _distributedCache.GetStringAsync($"SessionKey:{mobileId}");      // 微信会话密钥（解析openid时获取）
            if (string.IsNullOrEmpty(sessionKey))
            {
                throw Oops.Oh("会话密钥获取失败，请退出小程序后重新进入");
            }
            var phoneMsg = encrytedData.AESDecrypt(sessionKey, iv);     // 解密
            var json = JObject.Parse(phoneMsg);                         // 将返回的字符串转化为json
            var phone = json["purePhoneNumber"].Value<string>();        // 读取不带区号的手机号
            // 保存用户手机号
            await _service.UpdatePhoneAsync(new UserMobileEntity { Id = mobileId.Value, Phone = phone });
            return phone;
        }


        /// <summary>
        /// 保存微信用户头像
        /// </summary>
        /// <param name="faceUrl"></param>
        /// <returns></returns>
        private async Task<string> SaveFaceAsync(string faceUrl)
        {
            var url = App.Configuration["FileSystem:Url"];
            var body = new { item1 = faceUrl, item2 = IDGen.NextID() };
            var res = await $"{url}/api/user".SetBody(body).PostAsStringAsync();
            return res;
        }
    }

}
